<template>
  <div class="login-container">
    <div class="login-box">
      <h2>{{ isLogin ? '用户登录' : '用户注册' }}</h2>
      <el-form :model="formData">
        <el-form-item v-if="!isLogin">
          <el-input
              v-model="formData.name"
              placeholder="请输入用户名称"
              prefix-icon="User"
          />
        </el-form-item>
        <el-form-item>
          <el-input
              v-model="formData.account"
              placeholder="请输入账号"
              prefix-icon="User"
          />
        </el-form-item>
        <el-form-item>
          <el-input
              v-model="formData.password"
              type="password"
              placeholder="请输入密码"
              prefix-icon="Lock"
              show-password
              @keyup.enter="isLogin ? handleLogin() : handleRegister()"
          />
        </el-form-item>
        <el-form-item>
          <el-button
              type="primary"
              :loading="loading"
              @click="isLogin ? handleLogin() : handleRegister()"
              class="submit-button"
          >
            {{ isLogin ? '登录' : '注册' }}
          </el-button>
        </el-form-item>
        <div class="switch-mode">
          <el-button type="text" @click="switchMode">
            {{ isLogin ? '没有账号？立即注册' : '已有账号？立即登录' }}
          </el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onBeforeMount } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()
const loading = ref(false)
const isLogin = ref(true)

const formData = reactive({
  name: '',
  account: '',
  password: ''
})

// 在组件挂载前清除登录状态
onBeforeMount(() => {
  console.log('Login组件挂载前：清除所有登录状态')
  localStorage.clear()
  sessionStorage.clear()
})

// 切换登录/注册模式
const switchMode = () => {
  isLogin.value = !isLogin.value
  formData.name = ''
  formData.account = ''
  formData.password = ''
}

// 登录处理
const handleLogin = async () => {
  if (!formData.account || !formData.password) {
    ElMessage.warning('请输入账号和密码')
    return
  }

  try {
    loading.value = true
    const response = await fetch('/user/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        account: formData.account,
        password: formData.password
      }),
      credentials: 'include'
    })

    const result = await response.json()

    if (result.code === '200') {
      ElMessage.success('登录成功')
      localStorage.setItem('userId', result.data)
      router.push('/home')
    } else {
      ElMessage.error(result.message || '登录失败，请检查账号和密码')
    }
  } catch (error) {
    console.error('登录错误:', error)
    ElMessage.error('登录失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 注册处理
const handleRegister = async () => {
  if (!formData.name || !formData.account || !formData.password) {
    ElMessage.warning('请填写完整注册信息')
    return
  }

  try {
    loading.value = true
    const response = await fetch('/user/addUser', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        name: formData.name,
        account: formData.account,
        password: formData.password
      })
    })

    const result = await response.json()

    if (result.code === '200') {
      ElMessage.success('注册成功，请登录')
      isLogin.value = true  // 切换到登录界面
      formData.password = '' // 清空密码
    } else {
      ElMessage.error(result.message || '注册失败')
    }
  } catch (error) {
    console.error('注册错误:', error)
    ElMessage.error('注册失败，请稍后重试')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
}

.login-box {
  width: 400px;
  padding: 30px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}

.submit-button {
  width: 100%;
}

.el-form-item {
  margin-bottom: 20px;
}

.switch-mode {
  text-align: center;
  margin-top: 10px;
}

.switch-mode .el-button {
  font-size: 14px;
  color: #409EFF;
}

.switch-mode .el-button:hover {
  color: #66b1ff;
}
</style>
